package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private FriendApi friendApi;

    /**
     * 保存用户喜欢和不喜欢的用户
     * @param userLike
     * @return
     */
    @Override
    public boolean save(UserLike userLike) {
        long millis = System.currentTimeMillis();

        Query userLikeQuery = new Query(Criteria.where("userId").is(userLike.getUserId())
                .and("likeUserId").is(userLike.getLikeUserId()));
        if (mongoTemplate.exists(userLikeQuery, UserLike.class)) {
            Update update = new Update();
            update.set("updated", millis);
            update.set("isLike", userLike.getIsLike());
            mongoTemplate.updateFirst(userLikeQuery, update, UserLike.class);
        }else {
            userLike.setCreated(millis);
            userLike.setUpdated(millis);
            mongoTemplate.insert(userLike);
        }

        Query isLikeQuery = new Query(Criteria.where("userId").is(userLike.getLikeUserId())
                .and("likeUserId").is(userLike.getUserId())
                .and("isLike").is(true));
        if (mongoTemplate.exists(isLikeQuery, UserLike.class)) {
            friendApi.makeFriends(userLike.getUserId(), userLike.getLikeUserId());
            return true;
        }
        return false;
    }

    /**
     * 查询好友喜欢的用户
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<UserLike> findLikeByUserId(Long userId, Long page, Long pageSize) {
        Query query = new Query(Criteria.where("userId").is(userId).and("isLike").is(true));
        long count = mongoTemplate.count(query, UserLike.class);
        long start = (page - 1) * pageSize;
        List<UserLike> userLikes = new ArrayList();
        if(count > start) {
            query.skip(start).limit(pageSize.intValue());
            userLikes = mongoTemplate.find(query, UserLike.class);
        }

        return new PageResult<>(page, pageSize, count, userLikes);
    }

    /**
     * 用户是否相互喜欢
     *
     * @param userId
     * @param likeUserId
     * @return
     */
    @Override
    public boolean isLike(Long userId, Long likeUserId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId)
                .and("isLike").is(true));
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        if(null == userLike)
            return false;

        return userLike.getIsLike();
    }

    /**
     * 查找粉丝
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<UserLike> findFansByLikeUserId(Long userId, Long page, Long pageSize) {
        Query query = new Query(Criteria.where("likeUserId").is(userId).and("isLike").is(true));
        long start = (page - 1) * pageSize;
        long count = mongoTemplate.count(query, UserLike.class);
        List<UserLike> userLikes = new ArrayList<>();
        if(count > start) {
            query.skip(start).limit(pageSize.intValue());
            userLikes = mongoTemplate.find(query, UserLike.class);
        }

        return new PageResult<>(page, pageSize, count, userLikes);
    }

    /**
     * 查询相互喜欢的数量
     *
     * @param userId
     * @return
     */
    @Override
    public Integer findEachLoveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("isLike").is(true));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        if(CollectionUtils.isEmpty(userLikes))
            return 0;

        List<Long> userLikeIds = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        Query userLikeQuery = new Query();
        userLikeQuery.addCriteria(Criteria.where("userId").in(userLikeIds)
                .and("likeUserId").is(userId)
                .and("isLike").is(true));
        long count = mongoTemplate.count(userLikeQuery, UserLike.class);
        return (int)count;
    }

    /**
     * 查询喜欢的数量
     *
     * @param userId
     * @return
     */
    @Override
    public Integer findLoveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("isLike").is(true));
        return (int)mongoTemplate.count(query, UserLike.class);
    }

    /**
     * 查询粉丝的数量
     *
     * @param userId
     * @return
     */
    @Override
    public Integer findFansCount(Long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId)
                .and("isLike").is(true));
        return (int)mongoTemplate.count(query, UserLike.class);
    }

    /**
     * 修改是否喜欢
     *
     * @param userId
     * @param likeUserId
     */
    @Override
    public void update(Long userId, Long likeUserId, Boolean isLike) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId));
        Update update = new Update();
        update.set("isLike", isLike);
        mongoTemplate.updateFirst(query, update, UserLike.class);
    }

    /**
     * 查询用户喜欢的id
     *
     * @param userId
     * @param likeUserIds
     * @return
     */
    @Override
    public List<Long> findIsLikeUser(Long userId, List<Long> likeUserIds) {
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").in(likeUserIds).and("isLike").is(true));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        List<Long> ids = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        return ids;
    }
}
